package com.itbaizhan.shopping_seckill_service.redis;

import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.pojo.SeckillGoods;
import com.itbaizhan.shopping_common.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer container) {
        super(container);
    }

    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private SeckillService seckillService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key
        String key = message.toString();
        // 获取备份订单数据
        String orderId = key + "_copy";
        Orders orders = (Orders) redisTemplate.opsForValue().get(orderId);
        // 查询秒杀商品
        SeckillGoods seckillGoods = seckillService.findById(orders.getCartGoods().get(0).getGoodId());
        //回退库存
        seckillGoods.setStockCount(seckillGoods.getStockCount()+orders.getCartGoods().get(0).getNum());
        redisTemplate.boundHashOps("seckillGoods").put(seckillGoods.getGoodsId(),seckillGoods);
        // 删除备份订单数据
        redisTemplate.delete(orderId);
    }
}
